package com.ytjj.qmyx.mall.service.impl;

import com.ytjj.qmyx.mall.mapper.GroupBuyInfoMapper;
import com.ytjj.qmyx.mall.mapper.GroupBuyUserRelMapper;
import com.ytjj.qmyx.mall.model.GroupBuyInfo;
import com.ytjj.qmyx.mall.model.GroupBuyInfoExample;
import com.ytjj.qmyx.mall.model.ProductGroupBuyInfo;
import com.ytjj.qmyx.mall.model.ProductGroupBuyInfoExample;
import com.ytjj.qmyx.mall.model.response.groupbuy.ProcessGroupBuyListResponse;
import com.ytjj.qmyx.mall.service.YxGroupBuyInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class YxGroupBuyInfoServiceImpl implements YxGroupBuyInfoService {
    @Resource
    public GroupBuyInfoMapper groupBuyInfoMapper;
    @Resource
    public GroupBuyUserRelMapper groupBuyUserRelMapper;

    /**
     * 根据商品id查询成团数
     * @param productId
     * @return
     */
    @Override
    public long queryFinalGroupNumByProductId(Integer productId) {
        GroupBuyInfoExample example = new GroupBuyInfoExample();
        example.createCriteria().andProductIdEqualTo(productId).andFinalResultEqualTo((byte)1);
        long result = groupBuyInfoMapper.countByExample(example);
        return result;
    }

    /**
     * 正在拼团人数
     */
    @Override
    public Integer queryProcessGroupBuyNumByProductId(Integer productId) {
        return groupBuyUserRelMapper.queryProcessGroupBuyNumByProductId(productId);
    }

    /**
     * 正在拼团列表
     * @param productId
     * @return
     */
    @Override
    public List<ProcessGroupBuyListResponse> queryProcessGroupBuyList(Integer productId) {
        List<com.ytjj.qmyx.mall.model.ProcessGroupBuyListResponse> queryResult = groupBuyInfoMapper.queryProcessGroupBuyList(productId);
        List<ProcessGroupBuyListResponse> result = queryResult.stream().map(ProcessGroupBuyListResponse::new).collect(Collectors.toList());
        result.stream().forEach(s -> {
            s.setEndTimeSeconds((s.getEndTime().getTime() - System.currentTimeMillis()) / 1000L);
        });
        return result;
    }

    @Override
    public Integer insert(GroupBuyInfo groupBuyInfo) {
        return groupBuyInfoMapper.insertSelective(groupBuyInfo);
    }

    @Override
    public GroupBuyInfo selectById(Integer id) {
        return groupBuyInfoMapper.selectByPrimaryKey(id);
    }
}
